package com.faintlight.service.impl;

import com.faintlight.model.Philosophy;
import com.faintlight.model.User;
import com.faintlight.repository.PhilosophyRepository;
import com.faintlight.repository.UserRepository;
import com.faintlight.service.PhilosophyService;
import com.faintlight.exception.WarmException;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class PhilosophyServiceImpl implements PhilosophyService {

    private static final Logger logger = LoggerFactory.getLogger(PhilosophyServiceImpl.class);
    private final PhilosophyRepository philosophyRepository;
    private final UserRepository userRepository;

    @Override
    @Transactional
    public Philosophy savePhilosophy(Philosophy philosophy) {
        logger.info("📌 保存处世哲学: 内容长度={}", philosophy.getContent().length());

        User user = userRepository.findById(philosophy.getUser().getId())
                .orElseThrow(() -> new WarmException("用户不存在"));
        philosophy.setUser(user);

        Philosophy saved = philosophyRepository.save(philosophy);
        logger.info("✅ 处世哲学保存成功, ID={}", saved.getId());
        return saved;
    }

    @Override
    public List<Philosophy> getUserPhilosophies(Long userId) {
        logger.info("🔍 查询用户 {} 的处世哲学", userId);
        List<Philosophy> philosophies = philosophyRepository.findByUser_Id(userId);
        logger.info("✅ 查询成功, 共 {} 条记录", philosophies.size());
        return philosophies;
    }

    @Override
    @Transactional
    public void deletePhilosophy(Long id, Long userId) {
        Philosophy philosophy = philosophyRepository.findById(id)
                .orElseThrow(() -> new WarmException("未找到处世哲学"));
        if (!philosophy.getUser().getId().equals(userId)) {
            throw new WarmException("没有权限删除这条处世哲学");
        }
        philosophyRepository.delete(philosophy);
        logger.info("✅ 处世哲学删除成功, ID={}", id);
    }
}